import { NextResponse } from 'next/server'
import { AUTH_TOKEN, COOKIE_MAX_AGE } from '@/config/settings'
import jwt from '@/utils/jwt'
import userModule from '@/modules/user'

export async function GET(request) {
  const codeMap = { 0: '验证成功', 1: 'Token不可用' }
  const token = request.cookies.get(AUTH_TOKEN)?.value;
  if (!token) return NextResponse.json({ code: 1, codeMap, message: 'Invalid token' }, { status: 401 });
  try {
    const payload = await jwt.verify(token);
    if (payload) {
      const { id, username, nickname, avatar, mobile, email, status, roleInfo } = await userModule.getDetailed(payload.payload.username);
      const newToken = await jwt.generate({id, username, status, permissions: roleInfo.permissions.map(i => i.path) || [] });
      const response = NextResponse.json({ code: 0, codeMap, message: 'Success', userInfo: { id, username, nickname, avatar, mobile, email, roleInfo: { id: roleInfo.id, name: roleInfo.name, code: roleInfo.code, description: roleInfo.description, permissions: roleInfo.permissions } } });
      response.cookies.set(AUTH_TOKEN, newToken, { httpOnly: true, secure: false, maxAge: COOKIE_MAX_AGE, path: '/' });
      return response;
    } else {
      return NextResponse.json({ code: 1, codeMap, message: 'Invalid token' }, { status: 401 });
    }
  } catch (e) {
    return NextResponse.json({ code: 1, codeMap, message: 'Invalid token' }, { status: 401 })
  }
}